package com.micromall.web.security;

import com.alibaba.fastjson.JSON;
import com.micromall.utils.CommonEnvConstants;
import com.micromall.web.RequestContext;
import com.micromall.web.security.annotation.Authentication;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AdminAuthenticationInterceptor extends AbstractBaseInterceptor {

	private static final Logger logger             = LoggerFactory.getLogger(AdminAuthenticationInterceptor.class);
	private static final String _AUTHORIZED_HEADER = "X-Authorized";

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		if (CommonEnvConstants.DEBUG_ADMIN() && CommonEnvConstants.ENV.isDevEnv()) {
			return true;
		}
		String loginUser = (String)request.getSession().getAttribute(CommonEnvConstants.ADMIN_LOGIN_SESSION_KEY);
		if (StringUtils.isNotEmpty(loginUser)) {
			response.addHeader(_AUTHORIZED_HEADER, Boolean.TRUE.toString());
			RequestContext.setAdminLoginUser(loginUser);
			return true;
		}
		response.addHeader(_AUTHORIZED_HEADER, Boolean.FALSE.toString());
		Authentication authentication = _getHandlerAuthentication(handler);
		if ((isExclude(request) || (handler instanceof HandlerMethod && (authentication == null || !authentication.force())))) {
			return true;
		}
		response.sendRedirect(CommonEnvConstants.ADMIN_LOGIN_REDIRECT_URL);
		return false;
	}

	private Authentication _getHandlerAuthentication(Object handler) {
		Authentication authentication = null;
		if (handler instanceof HandlerMethod) {
			HandlerMethod handlerMethod = (HandlerMethod)handler;
			authentication = handlerMethod.getMethodAnnotation(Authentication.class);
			if (authentication == null) {
				authentication = handlerMethod.getBeanType().getAnnotation(Authentication.class);
			}
		}
		return authentication;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		logger.info("请求 [{}], 参数 [{}]", request.getRequestURI(), JSON.toJSONString(request.getParameterMap()));
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		if (ex != null) {
			logger.error("请求 [{}], 参数 [{}], 异常 [{}]", request.getRequestURI(), JSON.toJSONString(request.getParameterMap()), ex.getMessage());
		}
	}

}
